package com.step.sprite;

import javax.microedition.khronos.opengles.GL10;

import com.step.graphic.TextureRegion;
import com.step.sprite.animation.Animation2d;
import com.step.sprite.animation.KeyFrame2d;

/**
 * 二维动画精灵
 * @author heop
 *
 */
public class AnimatedSprite2D extends Sprite2D{
	Animation2d animation;
	private TextureRegion preRegion;
	
	public AnimatedSprite2D(Animation2d animation) {
		super(animation.getRegion().getTexture());
		preRegion = animation.getRegion();
	}

	public AnimatedSprite2D(KeyFrame2d... keyFrames) {
		super(keyFrames[0].getRegion());
		this.animation = new Animation2d(keyFrames);
		preRegion = keyFrames[0].getRegion();
	}
	
	public AnimatedSprite2D(TextureRegion...regions){
		super(regions[0]);
		int len = regions.length;
		KeyFrame2d[] keyFrames = new KeyFrame2d[len];
		
		for (int i = 0; i < len; i++) {
			keyFrames[i] = new KeyFrame2d(regions[i]);
		}
		this.animation = new Animation2d(keyFrames);
		preRegion = regions[0];
	}

	@Override
	public void draw(GL10 gl) {
		super.draw(gl);
		
		update();
	}
	
	public void draw(GL10 gl, RenderType renderType){
		super.draw(gl, renderType);
		update();
	}

	private void update(){
		if(animation == null) return;
		
		animation.update();
		
		TextureRegion curRegion = animation.getRegion();
		
		if(preRegion != curRegion){
			preRegion = curRegion;
			setRegion(curRegion);
		}
	}
	
	public Animation2d getAnimation() {
		return animation;
	}

	public void setAnimation(Animation2d animation) {
		this.animation = animation;
	}
}
